#include "T_PaintWidget.h"
#include <QGraphicsView>
#include <QHBoxLayout>
#include <QGlobalStatic>
#include <QFileDialog>
#include <QJsonDocument>

#include "T_GridScene.h"
#include "T_CustomRectItem.h"
#include "T_ModuleGroupRectItem.h"
#include "ElaMessageBar.h"
#include "ElaContentDialog.h"
#include "ElaPushButton.h"
#include "t_setparams.h"
#include "t_blockinfo.h"
#include "t_packinfo.h"
#include "t_result.h"
#include "t_excel.h"

Q_GLOBAL_STATIC(T_PaintWidget, s_instance)

T_PaintWidget::T_PaintWidget(QWidget * parent)
    : QWidget(parent)
{
    initView();
    initView1();
    initialze();
}

T_PaintWidget::~T_PaintWidget()
{

}

T_PaintWidget *T_PaintWidget::Instance()
{
    return s_instance;
}

void T_PaintWidget::ChangeGridVisible(bool is_visible)
{
    if(m_grid_scene != nullptr) {
        m_grid_scene->setGridVisible(is_visible);
    }
    if(m_grid_scene1!= nullptr) {
        m_grid_scene1->setGridVisible(is_visible);
    }
}

void T_PaintWidget::UpdateLineTip()
{
    if(m_grid_scene!= nullptr) {
        m_grid_scene->update(); 
    }
    if(m_grid_scene1!= nullptr) {
        m_grid_scene1->update();
    }
}

void T_PaintWidget::ExportImage()
{
    QString fileName = QFileDialog::getSaveFileName(this, "Save Image", "", "PNG Files (*.png)");
    if(fileName.isEmpty()) return;

    // 获取场景中所有元素的边界矩形
    QRectF rect = m_grid_scene->itemsBoundingRect();

    // 在边界矩形的基础上增加四周的边距
    int margin = 50; // 设置边距大小，可以根据需要调整
    rect.adjust(-margin, -margin, margin, margin); // 在四周增加边距

    // 设置场景的矩形区域
    m_grid_scene->setSceneRect(rect);

    // 创建一个足够大的 QImage
    QImage image(rect.size().toSize(), QImage::Format_ARGB32);
    image.fill(Qt::white);

    // 设置 QPainter 的渲染范围
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

    // 渲染场景
    m_grid_scene->render(&painter, QRectF(), rect);

    // 保存图片
    bool ret = image.save(fileName);
    if(ret) {
        ElaMessageBar::success(ElaMessageBarType::BottomRight,"导出图片","图片导出成功！",3000,this); 
    } else  {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"导出图片","图片导出失败！",3000,this); 
    }
}

QImage T_PaintWidget::GetImg()
{
    // 获取场景中所有元素的边界矩形
    QRectF rect = m_grid_scene->itemsBoundingRect();

    // 在边界矩形的基础上增加四周的边距
    int margin = 50; // 设置边距大小，可以根据需要调整
    rect.adjust(-margin, -margin, margin, margin); // 在四周增加边距

    // 设置场景的矩形区域
    m_grid_scene->setSceneRect(rect);

    // 创建一个足够大的 QImage
    QImage image(rect.size().toSize(), QImage::Format_ARGB32);
    image.fill(Qt::white);

    // 设置 QPainter 的渲染范围
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

    // 渲染场景
    m_grid_scene->render(&painter, QRectF(), rect);

    // 保存图片
    return image;
}

void T_PaintWidget::NewFile()
{
    if(!g_item_names.isEmpty()) {
        m_tip_dialog->exec();
    } else {

    }
}

void T_PaintWidget::ClearPaint()
{
    if(!g_item_names.isEmpty()) {
        m_clear_dialog->exec();
    }
}

void T_PaintWidget::SaveFile()
{
    if(m_main_rect == nullptr) {
        return;
    }
    //保存场景元素到json文件
    QString fileName = QFileDialog::getSaveFileName(this, "Save File", "", "JSON Files (*.json)");

    QJsonObject topLevel;
    topLevel["name"] = m_main_rect->getItemName(); 
    QPointF scene_pos = m_main_rect->mapToScene(m_main_rect->x(),m_main_rect->y());
    QPointF view_pos = m_graphics_view->mapFromScene(scene_pos);
    topLevel["x"] = qAbs(view_pos.x());
    topLevel["y"] = qAbs(view_pos.y());
    topLevel["width"] = m_main_rect->rect().width();
    topLevel["height"] = m_main_rect->rect().height();
    topLevel["color"] = m_main_rect->getItemData().color.name();
    topLevel["type"] = m_main_rect->getItemData().type;    
    topLevel["left_mar"] = m_main_rect->getMars(Left_Bottom);
    topLevel["top_mar"] = m_main_rect->getMars(Left_Top);
    topLevel["right_mar"] = m_main_rect->getMars(Right_Top);
    topLevel["bottom_mar"] = m_main_rect->getMars(Right_Bottom);

    // 处理三个数组
    topLevel["custom_array"] = processCustomItems(m_main_rect);
    topLevel["group_array"] = processGroupItems(m_main_rect);
    topLevel["outer_array"] = processOuterItems(); // 外层项目处理

    QJsonDocument doc;
    doc.setObject(topLevel);
    QByteArray jsonData = doc.toJson(QJsonDocument::Indented);
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        file.write(jsonData);
        file.close(); 
        ElaMessageBar::success(ElaMessageBarType::BottomRight,"保存模板","模板保存成功！",3000,this);
    } else {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"保存模板","模板保存失败！",3000,this); 
    }
}

void T_PaintWidget::OpenFile()
{
    //打开之前先询问是否需要保存当前场景内容
    if(!g_item_names.isEmpty()) {
        m_tip_dialog->setTitle("提示");
        m_tip_dialog->setSubTitle("是否确认清空当前场景，导入新的模板？");
        m_tip_dialog->exec();

        if(!m_is_import) {
            return;
        }
    }    

    //打开json文件
    QString fileName = QFileDialog::getOpenFileName(this, "Open File", "", "JSON Files (*.json)");
    if(fileName.isEmpty()) {
        ElaMessageBar::warning(ElaMessageBarType::BottomRight,"提示","没有选择模板文件！",3000,this);
        return;
    }
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"提示","模板文件打开失败！",3000,this);
        return;
    }
    QByteArray jsonData = file.readAll();
    //qDebug()<<jsonData.toStdString().c_str();
    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(jsonData);
    QJsonObject main_rect_json = doc.object();
    if (main_rect_json.isEmpty()) {
        ElaMessageBar::error(ElaMessageBarType::BottomRight,"提示","模板文件解析失败！",3000,this);
        return; 
    }

    //解析json数据
    cutomitem main_rect_data;
    main_rect_data.name = main_rect_json["name"].toString();
    main_rect_data.rect = QRectF(main_rect_json["x"].toDouble(),main_rect_json["y"].toDouble(),main_rect_json["width"].toDouble(),main_rect_json["height"].toDouble());
    main_rect_data.color = QColor(main_rect_json["color"].toString());
    main_rect_data.type = main_rect_json["type"].toInt();
    qreal left_mar = main_rect_json["left_mar"].toDouble();
    qreal top_mar = main_rect_json["top_mar"].toDouble();
    qreal right_mar = main_rect_json["right_mar"].toDouble();
    qreal bottom_mar = main_rect_json["bottom_mar"].toDouble();
    on_AddMainRect(main_rect_data,left_mar,top_mar,right_mar,bottom_mar);

    //解析添加item
    praseCustomItems(main_rect_json);
    praseGroupItems(main_rect_json);
    praseOuterItems(main_rect_json);
}

void T_PaintWidget::initialze()
{
    m_clear_dialog = new ElaContentDialog(this);
    m_clear_dialog->setMiddleButtonVisible(false);
    m_clear_dialog->setTitle("清空绘制");
    m_clear_dialog->setSubTitle("是否确认清空当前场景绘制图形？");
    m_clear_dialog->setLeftButtonText("确定");
    m_clear_dialog->setRightButtonText("取消");
    connect(m_clear_dialog,&ElaContentDialog::rightButtonClicked,this,[=](){
        m_clear_dialog->close();
        m_is_import = false;
    });
    connect(m_clear_dialog,&ElaContentDialog::leftButtonClicked,this,[=](){
        m_clear_dialog->close();
        clearPaint();
    });    

    T_ResultIns->hide();
    QVBoxLayout* vLayout_1 = new QVBoxLayout();
    vLayout_1->addWidget(T_SetParamsIns);
    vLayout_1->addSpacing(5);
    vLayout_1->addWidget(T_ResultIns);

    QHBoxLayout *hLayout_1 = new QHBoxLayout();
    hLayout_1->addLayout(vLayout_1);
    hLayout_1->addSpacing(5);
    hLayout_1->addWidget(m_graphics_view1);
    hLayout_1->addSpacing(5);
    hLayout_1->addWidget(m_graphics_view);
    hLayout_1->addSpacing(10);
    m_graphics_view1->hide();

    m_tbtn_export_excel = new ElaPushButton("导出评估表",this);
    connect(m_tbtn_export_excel, &ElaPushButton::clicked, this, [=]() {
        T_ExcelIns->WriteExcel();
    });
    QVBoxLayout *v_layout = new QVBoxLayout;
    v_layout->addStretch();
    v_layout->addWidget(m_tbtn_export_excel);

    QHBoxLayout *hLayout_2 = new QHBoxLayout();
    hLayout_2->addWidget(T_BlockInfoIns);
    hLayout_2->addStretch();
    hLayout_2->addWidget(T_PackInfoIns);
    hLayout_2->addSpacing(10);
    hLayout_2->addLayout(v_layout);
    hLayout_2->addStretch();
    T_BlockInfoIns->FlushInfo();

    QVBoxLayout* centerVLayout = new QVBoxLayout(this);
    centerVLayout->setContentsMargins(0, 0, 0, 0);
    centerVLayout->addLayout(hLayout_1);
    centerVLayout->addSpacing(5);
    centerVLayout->addLayout(hLayout_2);
    centerVLayout->addStretch();

    //初始化信号槽
    connect(T_SetParamsIns,&T_SetParams::addMainRect,this,&T_PaintWidget::on_AddMainRect);
    connect(T_SetParamsIns,&T_SetParams::addSubRect,this,&T_PaintWidget::on_AddSubRect);
    connect(T_SetParamsIns,&T_SetParams::addBlockRect,this,&T_PaintWidget::on_AddBlockRect);
    connect(T_SetParamsIns,&T_SetParams::clearScene,this,&T_PaintWidget::clearScene);
    connect(T_SetParamsIns,&T_SetParams::addOuterRect_paintLine,this,&T_PaintWidget::on_addOuterRect_paintLine);
    connect(T_SetParamsIns,&T_SetParams::addMainRect1,this,&T_PaintWidget::on_AddMainRect1);
    connect(T_SetParamsIns,&T_SetParams::addBlockRect1,this,&T_PaintWidget::on_AddBlockRect1);
    connect(T_SetParamsIns,&T_SetParams::addOuterRect_paintLine1,this,&T_PaintWidget::on_addOuterRect_paintLine1);
}

void T_PaintWidget::initView()
{
    m_graphics_view = new QGraphicsView(this);
    m_graphics_view->setMinimumHeight(550);
    m_graphics_view->setMinimumWidth(700);
    m_grid_scene = new T_GridScene(m_graphics_view);
    m_grid_scene->setSceneRect(0,0,m_graphics_view->width(),m_graphics_view->height());
    // m_graphics_view->setRenderHint(QPainter::Antialiasing,false);   //关闭抗锯齿
    m_graphics_view->setRenderHint(QPainter::Antialiasing, true); // 启用抗锯齿
    m_graphics_view->setRenderHint(QPainter::SmoothPixmapTransform, true); // 启用平滑变换
    // m_graphics_view->setInteractive(false);               // 禁用所有交互
    // m_graphics_view->setDragMode(QGraphicsView::NoDrag);  // 禁用拖拽模式
    m_graphics_view->setScene(m_grid_scene); //设置场景    

    //添加询问框
    m_tip_dialog = new ElaContentDialog(this);
    m_tip_dialog->setMiddleButtonVisible(false);
    m_tip_dialog->setTitle("新建模板");
    m_tip_dialog->setSubTitle("是否确认清空当前场景，新建模板？");
    m_tip_dialog->setLeftButtonText("确定");
    m_tip_dialog->setRightButtonText("取消");
    connect(m_tip_dialog,&ElaContentDialog::rightButtonClicked,this,[=](){
        m_tip_dialog->close();
        m_is_import = false;
    });
    connect(m_tip_dialog,&ElaContentDialog::leftButtonClicked,this,[=](){
        m_tip_dialog->close();
        clearScene();
    });
}

void T_PaintWidget::initView1()
{
    m_graphics_view1 = new QGraphicsView(this);
    m_graphics_view1->setMinimumHeight(600);
    m_graphics_view1->setMinimumWidth(200);
    m_grid_scene1 = new T_GridScene(m_graphics_view1);
    m_grid_scene1->setSceneRect(0,0,m_graphics_view1->width(),m_graphics_view1->height());
    // m_graphics_view->setRenderHint(QPainter::Antialiasing,false);   //关闭抗锯齿
    m_graphics_view1->setRenderHint(QPainter::Antialiasing, true); // 启用抗锯齿
    m_graphics_view1->setRenderHint(QPainter::SmoothPixmapTransform, true); // 启用平滑变换
    // m_graphics_view->setInteractive(false);               // 禁用所有交互
    // m_graphics_view->setDragMode(QGraphicsView::NoDrag);  // 禁用拖拽模式
    m_graphics_view1->setScene(m_grid_scene1); //设置场景    
}

void T_PaintWidget::clearScene()
{
    m_is_import = true;
    //重置主模块
    delete m_main_rect;
    m_main_rect = nullptr;

    delete m_main_rect1;
    m_main_rect1 = nullptr;
    //清楚场景所有item
    m_grid_scene->clear();
    //
    m_grid_scene1->clear();
    //清楚所有item名称，用于重新编号
    g_item_names.clear();
    //清除所有模块组名称
    g_item_group_names.clear();
}

void T_PaintWidget::clearPaint()
{
    clearScene();

    T_SetParamsIns->setAllowCreate(false);
    T_PackInfoIns->clearInfo();
}

QJsonArray T_PaintWidget::processCustomItems(T_CustomRectItem *parent)
{
    QRectF totalRect = parent->rect();
    QJsonArray array;
    foreach(QGraphicsItem* child, parent->childItems()) {
        if (auto customItem = dynamic_cast<T_CustomRectItem*>(child)) {
            if(!customItem->childItems().isEmpty()) {
                continue;
            }
            QJsonObject obj;
            // 只添加基本属性
            obj["name"] = customItem->getItemName();            
            QPointF scene_pos = parent->mapToScene(parent->x(),parent->y());
            QPointF view_pos = m_graphics_view->mapFromScene(scene_pos);
            QRectF tmp_rect = customItem->mapRectToParent(customItem->rect());
            if(parent->getItemData().type == Outer) {
                obj["x"] = outer_min_x_diff + tmp_rect.left() - totalRect.left(); //qAbs(view_pos.x());
                obj["y"] = outer_min_y_diff + tmp_rect.top() - totalRect.top(); //qAbs(view_pos.y());
            } else {
                obj["x"] = qAbs(view_pos.x()) + tmp_rect.left() - totalRect.left(); //qAbs(view_pos.x());
                obj["y"] = qAbs(view_pos.y()) + tmp_rect.top() - totalRect.top(); //qAbs(view_pos.y());
            }  
            // obj["x"] = qAbs(view_pos.x()) + tmp_rect.left() - totalRect.left(); //qAbs(view_pos.x());
            // obj["y"] = qAbs(view_pos.y()) + tmp_rect.top() - totalRect.top(); //qAbs(view_pos.y());
            obj["width"] = customItem->rect().width();
            obj["height"] = customItem->rect().height();
            obj["color"] = customItem->getItemData().color.name();
            obj["type"] = customItem->getItemData().type;
            
            array.append(obj);
        }
    }
    return array;
}

QJsonArray T_PaintWidget::processGroupItems(T_CustomRectItem *parent)
{
    QRectF totalRect = parent->rect();
    QJsonArray array;
    foreach(QGraphicsItem* child, parent->childItems()) {
        if (auto groupItem = dynamic_cast<T_ModuleGroupRectItem*>(child)) {
            // 填充group属性...
            //取一个内部矩形的大小和数量
            QList<QGraphicsItem *> items = groupItem->childItems();
            QGraphicsRectItem *rect_item = dynamic_cast<QGraphicsRectItem*>(items[0]);
            qreal width = rect_item->rect().width();
            qreal height = rect_item->rect().height();
            int num = items.count();          

            QJsonObject group_json;
            group_json["name"] = groupItem->getItemName();
            QPointF scene_pos = parent->mapToScene(parent->x(),parent->y());
            QPointF view_pos = m_graphics_view->mapFromScene(scene_pos);
            QRectF tmp_rect = groupItem->mapRectToParent(groupItem->rect());
            if(parent->getItemData().type == Outer) {
                group_json["x"] = outer_min_x_diff + tmp_rect.left() - totalRect.left(); //qAbs(view_pos.x());
                group_json["y"] = outer_min_y_diff + tmp_rect.top() - totalRect.top(); //qAbs(view_pos.y());
            } else {
                group_json["x"] = qAbs(view_pos.x()) + tmp_rect.left() - totalRect.left(); //qAbs(view_pos.x());
                group_json["y"] = qAbs(view_pos.y()) + tmp_rect.top() - totalRect.top(); //qAbs(view_pos.y());
            }           
            
            group_json["width"] = width;
            group_json["height"] = height;
            group_json["color"] = groupItem->getItemData().color.name();
            group_json["type"] = groupItem->getItemData().type;
            group_json["spacing"] = groupItem->getSpacing();
            group_json["num"] = num;
            group_json["mars_left"] = groupItem->getMars(Left_Bottom);
            group_json["mars_top"] = groupItem->getMars(Left_Top);
            group_json["mars_right"] = groupItem->getMars(Right_Top);
            group_json["mars_bottom"] = groupItem->getMars(Right_Bottom);
            group_json["direction"] = groupItem->getDirection();
            
            array.append(group_json);
        }
    }
    return array; 
}

QJsonArray T_PaintWidget::processOuterItems()
{
    QRectF totalRect = m_main_rect->rect();
    QJsonArray outerArray;

    // 假设您有获取外层项目的方法
    foreach(T_CustomRectItem* outerItem, getOuterItems()) {
        QJsonObject outerObj;        

        // 添加外层项目自身属性
        outerObj["name"] = outerItem->getItemName();        
        QPointF scene_pos = m_main_rect->mapToScene(m_main_rect->x(),m_main_rect->y());
        QPointF view_pos = m_graphics_view->mapFromScene(scene_pos);
        QRectF tmp_rect = outerItem->mapRectToParent(outerItem->rect());
        outerObj["x"] = qAbs(view_pos.x()) + tmp_rect.left() - totalRect.left(); //qAbs(view_pos.x());
        outerObj["y"] = qAbs(view_pos.y()) + tmp_rect.top() - totalRect.top(); //qAbs(view_pos.y());
        outer_min_x_diff = qAbs(view_pos.x()) + tmp_rect.left() - totalRect.left();
        outer_min_y_diff = qAbs(view_pos.y()) + tmp_rect.top() - totalRect.top();
        
        outerObj["width"] = outerItem->rect().width();
        outerObj["height"] = outerItem->rect().height();
        outerObj["color"] = outerItem->getItemData().color.name();
        outerObj["type"] = outerItem->getItemData().type;
        outerObj["left_mar"] = outerItem->getOuterMars(Left_Bottom);
        outerObj["top_mar"] = outerItem->getOuterMars(Left_Top);
        outerObj["right_mar"] = outerItem->getOuterMars(Right_Top);
        outerObj["bottom_mar"] = outerItem->getOuterMars(Right_Bottom);
        
        // 添加嵌套数组
        outerObj["custom_array"] = processCustomItems(outerItem);
        outerObj["group_array"] = processGroupItems(outerItem);
        
        outerArray.append(outerObj);
    }

    return outerArray; 
}

QList<T_CustomRectItem*> T_PaintWidget::getOuterItems()
{
    QList<T_CustomRectItem*> items;
    // 实现逻辑：可能是场景中的特定类型项目
    // 或与m_main_rect同级的项目等
    for(auto item : m_main_rect->childItems()) {
        if(T_CustomRectItem *customItem = dynamic_cast<T_CustomRectItem*>(item)) {
            if(customItem->childItems().isEmpty()) {
                continue;
            }
            
            items.append(customItem);
        }
    }

    return items;
}

void T_PaintWidget::praseCustomItems(const QJsonObject &obj)
{
    QJsonArray custom_array = obj["custom_array"].toArray();
    for (const QJsonValue &value : custom_array) {
        QJsonObject custom_json = value.toObject();
        cutomitem custom_data;
        custom_data.name = custom_json["name"].toString();
        custom_data.rect = QRectF(custom_json["x"].toDouble(),custom_json["y"].toDouble(),custom_json["width"].toDouble(),custom_json["height"].toDouble());
        custom_data.color = QColor(custom_json["color"].toString());
        custom_data.type = custom_json["type"].toInt();
        on_AddSubRect(custom_data);
    }
}

void T_PaintWidget::praseGroupItems(const QJsonObject &obj)
{
    QJsonArray group_array = obj["group_array"].toArray();
    for (const QJsonValue &value : group_array) {
        QJsonObject group_json = value.toObject();
        cutomitem group_data;
        group_data.name = group_json["name"].toString();
        group_data.rect = QRectF(group_json["x"].toDouble(),group_json["y"].toDouble(),group_json["width"].toDouble(),group_json["height"].toDouble());
        group_data.color = QColor(group_json["color"].toString());
        group_data.type = group_json["type"].toInt();
        double spacing = group_json["spacing"].toDouble();
        int num = group_json["num"].toInt();
        qreal mars_left = group_json["mars_left"].toDouble();
        qreal mars_top = group_json["mars_top"].toDouble();
        qreal mars_right = group_json["mars_right"].toDouble();
        qreal mars_bottom = group_json["mars_bottom"].toDouble();
        int direction = group_json["direction"].toInt();
        on_AddBlockRect_import(group_data,spacing,num,direction,mars_left,mars_top,mars_right,mars_bottom);       
    }
}

void T_PaintWidget::praseOuterItems(const QJsonObject &obj)
{
    QJsonArray outer_array = obj["outer_array"].toArray();
    for (const QJsonValue &value : outer_array){
        QJsonObject outer_json = value.toObject();
        cutomitem custom_data;
        custom_data.name = outer_json["name"].toString();
        custom_data.rect = QRectF(outer_json["x"].toDouble(),outer_json["y"].toDouble(),outer_json["width"].toDouble(),outer_json["height"].toDouble());
        custom_data.color = QColor(outer_json["color"].toString());
        custom_data.type = outer_json["type"].toInt();
        qreal mars_left = outer_json["left_mar"].toDouble();
        qreal mars_top = outer_json["top_mar"].toDouble();
        qreal mars_right = outer_json["right_mar"].toDouble();
        qreal mars_bottom = outer_json["bottom_mar"].toDouble();
        
        QJsonArray custom_array = outer_json["custom_array"].toArray(); 
        QJsonArray group_array = outer_json["group_array"].toArray();
        //添加外框
        on_AddOuterRect(custom_data,mars_left,mars_top,mars_right,mars_bottom,custom_array,group_array);
    }
}

void T_PaintWidget::on_AddMainRect(const cutomitem& data,qreal left_mar,qreal top_mar,qreal right_mar,qreal bottom_mar)
{
    if(m_main_rect != nullptr) {
        return; //只允许创建一个mainrect
    }
    //添加主体
    m_main_rect = new T_CustomRectItem();
    connect(T_SetParamsIns,&T_SetParams::cchildItemSpaceSignal,m_main_rect,&T_CustomRectItem::cchildItemSpaceSignal);
    connect(m_main_rect,&T_CustomRectItem::deleteMainItem,this,[=](){
        m_grid_scene->removeItem(m_main_rect);
        delete m_main_rect;
        m_main_rect = nullptr;
        m_grid_scene->update();
    });
    
    //整体坐标系统一句view场景坐标进行变换
    cutomitem tmp_item = data;
    QPointF scene_pos = m_graphics_view->mapToScene(data.rect.x(),data.rect.y());
    QPointF item_point = m_main_rect->mapFromScene(scene_pos.x(),scene_pos.y());
    tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
    m_main_rect->SetItemInfo(tmp_item);
    m_grid_scene->addItem(m_main_rect);

    m_main_rect->setMars(left_mar,top_mar,right_mar,bottom_mar);
}

void T_PaintWidget::on_AddMainRect1(const cutomitem &data, qreal leftMar, qreal topMar, qreal rightMar, qreal bottomMar)
{
    if(m_main_rect1 != nullptr) {
        return; //只允许创建一个mainrect
    }
    //添加主体
    m_main_rect1 = new T_CustomRectItem();
    m_main_rect1->setIsText(false);
    connect(T_SetParamsIns,&T_SetParams::cchildItemSpaceSignal,m_main_rect1,&T_CustomRectItem::cchildItemSpaceSignal);
    connect(m_main_rect1,&T_CustomRectItem::deleteMainItem,this,[=](){
        m_grid_scene1->removeItem(m_main_rect1);
        delete m_main_rect1;
        m_main_rect1 = nullptr;
        m_grid_scene1->update();
    });

    //整体坐标系统一句view场景坐标进行变换
    cutomitem tmp_item = data;
    QPointF scene_pos = m_graphics_view1->mapToScene(data.rect.x(),data.rect.y());
    QPointF item_point = m_main_rect1->mapFromScene(scene_pos.x(),scene_pos.y());
    tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
    m_main_rect1->SetItemInfo(tmp_item);
    m_grid_scene1->addItem(m_main_rect1);

    m_main_rect1->setMars(leftMar,topMar,rightMar,bottomMar);
}

void T_PaintWidget::on_AddSubRect(const cutomitem& data)
{
    if(m_main_rect == nullptr) {
        return;
    }

    if(data.type == Module) {
        //添加子项
        T_CustomRectItem *rect = new T_CustomRectItem();
        connect(rect,&T_CustomRectItem::flushMainLayout,[&](){
            m_main_rect->updateLayout();
        });

        //整体坐标系统一句scene场景坐标进行变换
        cutomitem tmp_item = data;
        QPointF scene_pos = m_graphics_view->mapToScene(data.rect.x(),data.rect.y());
        QPointF item_point = rect->mapFromScene(scene_pos.x(),scene_pos.y());
        tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
        rect->SetItemInfo(tmp_item);
        //m_grid_scene->addItem(rect);    
        m_main_rect->addChild(rect);
    } else if(data.type == Block) {
        //创建模块组
        T_ModuleGroupRectItem *group = new T_ModuleGroupRectItem();
        connect(group, &T_ModuleGroupRectItem::flushMainRect, [this]() {
            m_main_rect->updateLayout();
        });
        // 为 m_main_rect 连接信号和槽，触发 group 的 updateLayout
        connect(m_main_rect, &T_CustomRectItem::flushBlockLayout, group, &T_ModuleGroupRectItem::updateLayout);    

        group->setSpacing(5.0);         // 设置间距        
        group->setLayoutDirection(T_ModuleGroupRectItem::Horizontal); // 切换为水平布局       

        cutomitem tmp_item = data;
        QPointF scene_pos = m_graphics_view->mapToScene(data.rect.x(),data.rect.y());
        QPointF item_point = group->mapFromScene(scene_pos.x(),scene_pos.y());
        tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
        group->SetItemInfo(tmp_item);
        m_main_rect->addChild(group);

        // 创建子矩形并添加到组        
        T_CustomRectItem *rectItem = new T_CustomRectItem();
        connect(rectItem,&T_CustomRectItem::flushSignalBlockLayout,group,&T_ModuleGroupRectItem::updateLayout);
        tmp_item.name = "";
        rectItem->SetItemInfo(tmp_item);
        group->addRectangle(rectItem);
    }    
}

void T_PaintWidget::on_AddBlockRect(const cutomitem& data,double space,int num,int direction)
{
    if(m_main_rect == nullptr) {
        return;
    }

    //添加模块，根据排列方式和数量自动创建
    T_ModuleGroupRectItem *group = new T_ModuleGroupRectItem();

    // 为当前创建的 group 连接信号和槽
    connect(group, &T_ModuleGroupRectItem::flushMainRect, [this]() {
        m_main_rect->updateLayout();
    });

    // 为 m_main_rect 连接信号和槽，触发 group 的 updateLayout
    connect(m_main_rect, &T_CustomRectItem::flushBlockLayout, group, &T_ModuleGroupRectItem::updateLayout);    

    group->setSpacing(space);         // 设置间距
    group->setMars(g_duan_value_V,g_duan_value_H,g_duan_value_V,g_duan_value_H);

    if(direction == 0) {
        group->setLayoutDirection(T_ModuleGroupRectItem::Horizontal); // 切换为水平布局
    } else if(direction == 1) {
        group->setLayoutDirection(T_ModuleGroupRectItem::Vertical); // 切换为垂直布局
    } else if(direction == 2) {
        group->setLayoutDirection(T_ModuleGroupRectItem::DD); // 切换为垂直布局
        num = 1;
    }

    cutomitem tmp_item = data;
    QPointF scene_pos = m_graphics_view->mapToScene(data.rect.x(),data.rect.y());
    QPointF item_point = group->mapFromScene(scene_pos.x(),scene_pos.y());
    tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
    group->SetItemInfo(tmp_item);
    m_main_rect->addChild(group);
    // 创建子矩形并添加到组
    for(int i = 0; i < num; i++){
        QGraphicsRectItem *rectItem = new QGraphicsRectItem();
        rectItem->setRect(tmp_item.rect);
        rectItem->setBrush(QColor(tmp_item.color));
        group->addRectangle(rectItem);
    }
}

void T_PaintWidget::on_AddBlockRect1(const cutomitem &data, double space, int num, int direction)
{
    if(m_main_rect1 == nullptr) {
        return;
    }

    //添加模块，根据排列方式和数量自动创建
    T_ModuleGroupRectItem *group = new T_ModuleGroupRectItem();

    // 为当前创建的 group 连接信号和槽
    connect(group, &T_ModuleGroupRectItem::flushMainRect, [this]() {
        m_main_rect1->updateLayout();
    });

    // 为 m_main_rect 连接信号和槽，触发 group 的 updateLayout
    connect(m_main_rect1, &T_CustomRectItem::flushBlockLayout, group, &T_ModuleGroupRectItem::updateLayout);

    group->setSpacing(space);         // 设置间距
    group->setMars(g_duan_value_V,g_duan_value_H,g_duan_value_V,g_duan_value_H);

    if(direction == 0) {
        group->setLayoutDirection(T_ModuleGroupRectItem::Horizontal); // 切换为水平布局
    } else if(direction == 1) {
        group->setLayoutDirection(T_ModuleGroupRectItem::Vertical); // 切换为垂直布局
    } else if(direction == 2) {
        group->setLayoutDirection(T_ModuleGroupRectItem::DD); // 切换为垂直布局
        num = 1;
    }

    cutomitem tmp_item = data;
    QPointF scene_pos = m_graphics_view1->mapToScene(data.rect.x(),data.rect.y());
    QPointF item_point = group->mapFromScene(scene_pos.x(),scene_pos.y());
    tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
    group->SetItemInfo(tmp_item);
    m_main_rect1->addChild(group);
    // 创建子矩形并添加到组
    for(int i = 0; i < num; i++){
        QGraphicsRectItem *rectItem = new QGraphicsRectItem();
        rectItem->setRect(tmp_item.rect);
        rectItem->setBrush(QColor(tmp_item.color));
        group->addRectangle(rectItem);
    }
}

void T_PaintWidget::on_AddBlockRect_import(const cutomitem &data, double space, int num, int direction
                                            , qreal leftMar, qreal topMar, qreal rightMar, qreal bottomMar)
{
    if(m_main_rect == nullptr) {
        return;
    }

    //添加模块，根据排列方式和数量自动创建
    T_ModuleGroupRectItem *group = new T_ModuleGroupRectItem();
    // 为当前创建的 group 连接信号和槽
    connect(group, &T_ModuleGroupRectItem::flushMainRect, [this]() {
        m_main_rect->updateLayout();
    });
    // 为 m_main_rect 连接信号和槽，触发 group 的 updateLayout
    connect(m_main_rect, &T_CustomRectItem::flushBlockLayout, group, &T_ModuleGroupRectItem::updateLayout);    

    group->setSpacing(space);         // 设置间距
    group->setMars(topMar,leftMar,bottomMar,rightMar);

    if(direction == 0) {
        group->setLayoutDirection(T_ModuleGroupRectItem::Horizontal); // 切换为水平布局
    } else if(direction == 1) {
        group->setLayoutDirection(T_ModuleGroupRectItem::Vertical); // 切换为垂直布局
    }

    cutomitem tmp_item = data;
    QPointF scene_pos = m_graphics_view->mapToScene(data.rect.x(),data.rect.y());
    QPointF item_point = group->mapFromScene(scene_pos.x(),scene_pos.y());
    tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
    group->SetItemInfo(tmp_item);
    m_main_rect->addChild(group);
    // 创建子矩形并添加到组
    for(int i = 0; i < num; i++){
        // QGraphicsRectItem *rectItem = new QGraphicsRectItem();
        // rectItem->setRect(tmp_item.rect);
        // rectItem->setBrush(QColor(tmp_item.color));
        // group->addRectangle(rectItem);
        T_CustomRectItem *rectItem = new T_CustomRectItem();
        connect(rectItem,&T_CustomRectItem::flushSignalBlockLayout,group,&T_ModuleGroupRectItem::updateLayout);
        tmp_item.name = "";
        rectItem->SetItemInfo(tmp_item);
        group->addRectangle(rectItem);
    }

    //m_grid_scene->addItem(group);
}

void T_PaintWidget::on_AddOuterRect(const cutomitem &data,qreal leftMar,qreal topMar,qreal rightMar,qreal bottomMar
                                    ,const QJsonArray& custom_array,const QJsonArray& group_array)
{
    //添加子项
    T_CustomRectItem *outerRect = new T_CustomRectItem();
    connect(outerRect,&T_CustomRectItem::flushMainLayout,[&](){
        m_main_rect->updateLayout();
    });

    //整体坐标系统一句scene场景坐标进行变换
    cutomitem tmp_item = data;
    QPointF scene_pos = m_graphics_view->mapToScene(data.rect.x(),data.rect.y());
    QPointF item_point = outerRect->mapFromScene(scene_pos.x(),scene_pos.y());
    tmp_item.rect = QRectF(item_point.x(),item_point.y(),data.rect.width(),data.rect.height());
    outerRect->SetItemInfo(tmp_item);  
    m_main_rect->addChild(outerRect);
    outerRect->setMars(leftMar,topMar,rightMar,bottomMar);

    for (const QJsonValue &value : custom_array) {
        QJsonObject custom_json = value.toObject();
        cutomitem custom_data;
        custom_data.name = custom_json["name"].toString();
        custom_data.rect = QRectF(custom_json["x"].toDouble(),custom_json["y"].toDouble(),custom_json["width"].toDouble(),custom_json["height"].toDouble());
        custom_data.color = QColor(custom_json["color"].toString());
        custom_data.type = custom_json["type"].toInt();

        T_CustomRectItem *item = new T_CustomRectItem();
        connect(item,&T_CustomRectItem::flushMainLayout,outerRect,&T_CustomRectItem::updateLayout);
        cutomitem tmp_item = custom_data;
        QPointF scene_pos = m_graphics_view->mapToScene(custom_data.rect.x(),custom_data.rect.y());
        QPointF item_point = item->mapFromScene(scene_pos.x(),scene_pos.y());
        tmp_item.rect = QRectF(item_point.x(),item_point.y(),custom_data.rect.width(),custom_data.rect.height());
        item->SetItemInfo(tmp_item);  
        outerRect->addChild(item);
    }

    for (const QJsonValue &value : group_array) {
        QJsonObject group_json = value.toObject();
        cutomitem group_data;
        group_data.name = group_json["name"].toString();
        group_data.rect = QRectF(group_json["x"].toDouble(),group_json["y"].toDouble(),group_json["width"].toDouble(),group_json["height"].toDouble());
        group_data.color = QColor(group_json["color"].toString());
        group_data.type = group_json["type"].toInt();
        double spacing = group_json["spacing"].toDouble();
        int num = group_json["num"].toInt();
        qreal mars_left = group_json["mars_left"].toDouble();
        qreal mars_top = group_json["mars_top"].toDouble();
        qreal mars_right = group_json["mars_right"].toDouble();
        qreal mars_bottom = group_json["mars_bottom"].toDouble();
        int direction = group_json["direction"].toInt();

        //添加模块，根据排列方式和数量自动创建
        T_ModuleGroupRectItem *group = new T_ModuleGroupRectItem();
        // 为当前创建的 group 连接信号和槽
        connect(group, &T_ModuleGroupRectItem::flushMainRect, outerRect,&T_CustomRectItem::updateLayout);
        // 为 outerRect 连接信号和槽，触发 group 的 updateLayout
        connect(outerRect, &T_CustomRectItem::flushBlockLayout, group, &T_ModuleGroupRectItem::updateLayout);    

        group->setSpacing(spacing);         // 设置间距
        group->setMars(mars_top,mars_left,mars_bottom,mars_right);

        if(direction == 0) {
            group->setLayoutDirection(T_ModuleGroupRectItem::Horizontal); // 切换为水平布局
        } else if(direction == 1) {
            group->setLayoutDirection(T_ModuleGroupRectItem::Vertical); // 切换为垂直布局
        }

        cutomitem tmp_item = group_data;
        QPointF scene_pos = m_graphics_view->mapToScene(group_data.rect.x(),group_data.rect.y());
        QPointF item_point = group->mapFromScene(scene_pos.x(),scene_pos.y());
        tmp_item.rect = QRectF(item_point.x(),item_point.y(),group_data.rect.width(),group_data.rect.height());
        group->SetItemInfo(tmp_item);
        outerRect->addChild(group);
        // 创建子矩形并添加到组
        for(int i = 0; i < num; i++){
            T_CustomRectItem *rectItem = new T_CustomRectItem();
            connect(rectItem,&T_CustomRectItem::flushSignalBlockLayout,group,&T_ModuleGroupRectItem::updateLayout);
            tmp_item.name = "";
            rectItem->SetItemInfo(tmp_item);
            group->addRectangle(rectItem);
        }
    }
}

void T_PaintWidget::ResizeView()
{
    if(m_graphics_view == nullptr || m_grid_scene == nullptr || m_main_rect == nullptr) {
        return;
    }

    // QPointF pointF = m_graphics_view->mapToScene(QPoint(0,0));
    // m_main_rect->setPos(pointF);

    // QRectF totalRect = m_grid_scene->itemsBoundingRect();
    // QRectF viewRect = totalRect.adjusted(-25, -25, 25, 25);

    // m_graphics_view->fitInView(viewRect, Qt::KeepAspectRatio);

    // 获取场景的边界矩形
    QRectF totalRect = m_grid_scene->itemsBoundingRect();
    // 添加一些边距
    QRectF viewRect = totalRect.adjusted(-25, -25, 25, 25);

    // 设置场景矩形以确保滚动条等工作正常
    m_grid_scene->setSceneRect(viewRect);

    // 首先确保视图可以显示整个场景
    m_graphics_view->fitInView(viewRect, Qt::KeepAspectRatio);

    // 然后计算居中偏移
    QSize viewSize = m_graphics_view->viewport()->size();
    QSizeF sceneSize = m_graphics_view->transform().mapRect(viewRect).size();

    // 只有在视图比场景大的情况下才需要手动居中
    if (viewSize.width() > sceneSize.width() || viewSize.height() > sceneSize.height()) {
        // 计算水平和垂直偏移
        double hOffset = (viewSize.width() - sceneSize.width()) / 2.0;
        double vOffset = (viewSize.height() - sceneSize.height()) / 2.0;

        // 应用偏移
        m_graphics_view->translate(hOffset / m_graphics_view->transform().m11(),
                                    vOffset / m_graphics_view->transform().m22());
    }
}

void T_PaintWidget::ResizeView1()
{
    if(m_graphics_view1 == nullptr || m_grid_scene1 == nullptr || m_main_rect1 == nullptr) {
        return;
    }

    // QPointF pointF = m_graphics_view1->mapToScene(QPoint(0,0));
    // m_main_rect1->setPos(pointF);

    // QRectF totalRect = m_grid_scene1->itemsBoundingRect();
    // QRectF viewRect = totalRect.adjusted(-25, -25, 25, 25);

    // m_graphics_view1->fitInView(viewRect, Qt::KeepAspectRatio);

    // 获取场景的边界矩形
    QRectF totalRect = m_grid_scene1->itemsBoundingRect();
    // 添加一些边距
    QRectF viewRect = totalRect.adjusted(-25, -25, 25, 25);

    // 设置场景矩形以确保滚动条等工作正常
    m_grid_scene1->setSceneRect(viewRect);

    // 首先确保视图可以显示整个场景
    m_graphics_view1->fitInView(viewRect, Qt::KeepAspectRatio);

    // 然后计算居中偏移
    QSize viewSize = m_graphics_view1->viewport()->size();
    QSizeF sceneSize = m_graphics_view1->transform().mapRect(viewRect).size();

    // 只有在视图比场景大的情况下才需要手动居中
    if (viewSize.width() > sceneSize.width() || viewSize.height() > sceneSize.height()) {
        // 计算水平和垂直偏移
        double hOffset = (viewSize.width() - sceneSize.width()) / 2.0;
        double vOffset = (viewSize.height() - sceneSize.height()) / 2.0;

        // 应用偏移
        m_graphics_view1->translate(hOffset / m_graphics_view1->transform().m11(),
                                    vOffset / m_graphics_view1->transform().m22());
    }
}

void T_PaintWidget::on_addOuterRect_paintLine(const QStringList &tmpList)
{
    if(m_main_rect == nullptr) {
        return;
    }

    m_main_rect->addOuterRect_paintLine(tmpList);
}

void T_PaintWidget::on_addOuterRect_paintLine1(const QStringList &tmpList)
{
    if(m_main_rect1 == nullptr) {
        return;
    }

    m_main_rect1->addOuterRect_paintLine(tmpList);
}

void T_PaintWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);

    ResizeView();
    ResizeView1();
}
